package com.googlecode.wannabet.controller.ui;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.googlecode.wannabet.domain.WannabetUser;

public class IndexController extends Controller {

	@Override
	protected Navigation run() throws Exception {
		UserService userService = UserServiceFactory.getUserService();
		
		String url = null;
		boolean loggedIn = false;
		
		String thisURL = request.getRequestURI();
		if(request.getUserPrincipal() == null) {
			url = userService.createLoginURL(thisURL);
		} else {
			loggedIn = true;
			url = userService.createLogoutURL(thisURL);
			requestScope("userName", request.getUserPrincipal().getName());
			
			// only create the user in database if the user is an admin
			if(userService.isUserAdmin()) {
				checkAndAddUserIfNeeded(userService.getCurrentUser());
			}
		}
		
		requestScope("url", url);
		requestScope("loggedIn", loggedIn);
		
		return forward("/jsps/index.jsp");
	}

	private void checkAndAddUserIfNeeded(User user) {
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		Query query = new Query("WannabetUser");
		query.addFilter("email", Query.FilterOperator.EQUAL, user.getEmail());
		PreparedQuery preparedQuery = datastore.prepare(query);

		int count = preparedQuery.countEntities();
		if(count == 0) {
			Entity u = WannabetUser.getEntity(user.getUserId(), user.getEmail(), user.getNickname());
			
			datastore.put(u);
		}
	}

}
